Python Essentials by A Rapid Guide to the Fundamental Features of Python

Python Essentials by A Rapid Guide to the Fundamental Features of Python
Author: A Rapid Guide to the Fundamental Features of Python
Language: eng
Format: mobi, epub
Publisher: Packt Publishing

Wait. What just happened? How is this possible?

As a hint, we'll need to search through the code for an object with a hidden, shared state. Earlier, we noted that a default list object would be a problem. This hidden list object is getting reused.

What happens is this:

When the def statement is executed, the expressions that define the parameter defaults are evaluated. This means that a single mutable list object is created as the default object for the collection parameter.

When the more_dice() function is evaluated without an argument for the collection parameter, the one-and-only mutable list object is used as the default object. What's important is that a single mutable object is being reused. If, at any point, we update this object, that mutation applies to all shared uses of the object. Since it's returned by the function, this single list could be assigned to several variables.

When the more_dice() function is evaluated a second time without an argument for the collection parameter, the mutated list object is re-used as the default.